import React from 'react';
import {Card,Form,Input,Button,message} from 'antd';
import axios from '../common/axios';

import Rules from '../common/rules';

import {connect} from 'react-redux';


export default connect((state, props)=>{
  return props;
}, dispatch=>({
  setToken: (token,token_expires,access)=>dispatch({type: 'set_token', value: {token,token_expires,access}})
}))(Form.create({
  username: '',
  password: ''
})(props=>{
  const {setToken}=props;
  const {getFieldDecorator, validateFields}=props.form;

  let fnLogin=ev=>{
    ev.preventDefault();

    validateFields(async (err, values)=>{
      if(!err){
        try{
          let {data}=await axios({
            url: '/login',
            method: 'post',
            data: values
          });

          const {token,token_expires,access}=data;

          setToken(token, token_expires, access);
          message.success('登录成功');
        }catch(e){
          const {msg}=e.response.data;
          message.error(msg);
          console.log(e);
        }
      }
    });
  };

  let fnReg=ev=>{
    ev.preventDefault();

    validateFields(async (err, values)=>{
      if(!err){
        // console.log('reg', values);
        try{
          let {data}=await axios({
            url: '/reg',
            method: 'post',
            data: values
          });

          console.log(data);
        }catch(e){
          console.log(e.response);
        }

      }
    });
  };

  return (
    <Card title="登录" className="dialog">
      <Form>
        <Form.Item>
          {getFieldDecorator('username', {
            rules: Rules.admin_username
          })(
            <Input type="text" placeholder="请输入用户名" />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('password', {
            rules: Rules.admin_password
          })(
            <Input type="password" placeholder="请输入密码" />
          )}
        </Form.Item>
        <Form.Item>
          <Button type="primary" onClick={fnLogin}>登录</Button>
          <Button type="default" onClick={fnReg}>注册</Button>
        </Form.Item>
      </Form>
    </Card>
  );
}));
